package com.asktgapp.user.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.asktgapp.R;
import com.asktgapp.adapter.BrandAdapter;
import com.asktgapp.adapter.MyBrandAdapter;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.BrandVO;
import com.asktgapp.model.Person;
import com.asktgapp.widget.WordsNavigation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/29
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class ChooseBrandFragment extends BaseFragment{


    private BrandAdapter mBAdapter;
//    private List<BrandVO> list;
    private String typeId;
    private String brandId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_choose_brand, container, false);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }


    public static ChooseBrandFragment newInstance(String typeId) {
        ChooseBrandFragment fragment = new ChooseBrandFragment();
        Bundle bundle = new Bundle();
        bundle.putString("typeId", typeId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        Bundle bundle = getArguments();
        typeId = bundle.getString("typeId");
        final ListView  mBrandListView = rootView.findViewById(R.id.list);
        final WordsNavigation mBrandWordNavigation = rootView.findViewById(R.id.words);
//        mBrandWordNavigation.setOnWordsChangeListener(this);

        mBAdapter = new BrandAdapter(getActivity(), new BrandAdapter.ItemCallback() {
            @Override
            public void onItemClick(String string, String id) {
                Intent intent = new Intent();
                intent.putExtra("brand", string);
                intent.putExtra("brandId", id);
                getActivity().setResult(Activity.RESULT_OK, intent);
                getActivity().finish();
            }

            @Override
            public void onDataSetComplete() {
                dismissProgress();
            }

            @Override
            public void onStartSetData() {
                showProgress(getClass().getSimpleName());
            }
        });

        mBrandListView.setAdapter(mBAdapter);

        mBrandListView.setOnScrollListener(new AbsListView.OnScrollListener(){

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (mBAdapter.getData().size() > 0) {
                    if (mBAdapter.getData().get(firstVisibleItem).getHeadChar().equals("热门品牌")) {
                        mBrandWordNavigation.setTouchIndex("#");
                    } else {
                        mBrandWordNavigation.setTouchIndex(mBAdapter.getData().get(firstVisibleItem).getHeadChar().toUpperCase());
                    }
                }
            }
        });
        mBrandWordNavigation.setOnWordsChangeListener(new WordsNavigation.onWordsChangeListener() {
            @Override
            public void wordsChange(String words) {
                if (words.equals("#")) {
                    words = "热门品牌";
                }

                for (int i = 0; i < mBAdapter.getData().size(); i++) {
                    if (mBAdapter.getData().get(i).getHeadChar().equals(words)) {
                        mBrandListView.setSelection(i);
                        return;
                    }
                    String headerWord = mBAdapter.getData().get(i).getHeadChar().toUpperCase();
                    //将手指按下的字母与列表中相同字母开头的项找出来
                    if (words.equals(headerWord)) {
                        //将列表选中哪一个
                        mBrandListView.setSelection(i);
                        //找到开头的一个即可
                        return;
                    }
                }
            }
        });

    }

//    /**
//     * 初始化联系人列表信息
//     */
//    private void initData() {
//        mBAdapter.setData(list);
//        //对集合排序
////        Collections.sort(list, new Comparator<BrandVO>() {
////            @Override
////            public int compare(BrandVO lhs, BrandVO rhs) {
////                //根据拼音进行排序
////                return lhs.getPinyin().compareTo(rhs.getPinyin());
////            }
////        });
//
//
////        mBrandAdapter = new MyBrandAdapter(getActivity(), list, new MyBrandAdapter.ItemCallback() {
////            @Override
////            public void onItemClick(String string, String id) {
////                Intent intent = new Intent();
////                intent.putExtra("brand", string);
////                intent.putExtra("brandId", id);
////                getActivity().setResult(Activity.RESULT_OK, intent);
////                getActivity().finish();
//////                showTost(string, 0);
////            }
////        });
//
//
//    }

    @Override
    public void loadData() {

        getBrandLlist();
    }

    private void getBrandLlist() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("typeId", typeId);
        Call<ApiResponseBody<List<BrandVO>>> call = apiservice.getBrandList(params);
        call.enqueue(new Callback<ApiResponseBody<List<BrandVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<BrandVO>>> call, Response<ApiResponseBody<List<BrandVO>>> response) {
                if (response.isSuccessful()) {
                   List<BrandVO> list = response.body().getResult();
                    if (list.size() == 0) {
                        visibleNoData();
                        dismissProgress();
                    } else
                        mBAdapter.setData(list);
                } else {
                    showTost(response.raw().message(), 1);
                    dismissProgress();
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<BrandVO>>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);

            }
        });

    }

//    //继承自右边的字母索引表控件
//    @Override
//    public void onScrollStateChanged(AbsListView view, int scrollState) {
//
//    }
//
//    @Override
//    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
////        if (mBAdapter.getData().size() > 0) {
////            //当滑动列表的时候，更新右侧字母列表的选中状态
////            if (mBAdapter.getData().get(firstVisibleItem).getHeadChar().equals("热门品牌")) {
////                mBrandWordNavigation.setTouchIndex("#");
////            } else {
////                mBrandWordNavigation.setTouchIndex(mBAdapter.getData().get(firstVisibleItem).getHeadChar().toUpperCase());
////            }
////        }
//
//    }

//    @Override
//    public void wordsChange(String words) {
//        updateListView(words);
//    }
//
//    /**
//     * @param words 首字母
//     */
//    private void updateListView(String words) {
//        if (words.equals("#")) {
//            words = "热门品牌";
//        }
//        if(mBrandAdapter==null)
//            return;
//        for (int i = 0; i < mBrandAdapter.getData().size(); i++) {
//            if (mBrandAdapter.getData().get(i).getHeadChar().equals(words)) {
//                mBrandListView.setSelection(i);
//                return;
//            }
//            String headerWord = mBrandAdapter.getData().get(i).getHeadChar().toUpperCase();
//            //将手指按下的字母与列表中相同字母开头的项找出来
//            if (words.equals(headerWord)) {
//                //将列表选中哪一个
//                mBrandListView.setSelection(i);
//                //找到开头的一个即可
//                return;
//            }
//        }
//    }

}
